<?php
class Search_Form_RegularMobileForm extends Ac_Form
{
    private $settings;

    protected $elementCheckBoxDecorators = array(
        'ViewHelper',
        'Errors',
       // 'Description'
        //array(array('data' => 'HtmlTag'), array('tag' => 'td', 'class' => 'element')),
        array('Label', array('placement' => 'APPEND')),
        //array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class'=>'inputText')),
    );

    protected $elementDecorators = array(
        'ViewHelper',
        'Errors',
        //'Description'
        //array(array('data' => 'HtmlTag'), array('tag' => 'td', 'class' => 'element')),
        array('Label', array('placement' => 'PREPEND')),
        array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class'=>'inputText')),
    );

    protected $selectElementDecorators = array(
        'ViewHelper',
        'Errors',
       // 'Description'
        //array(array('data' => 'HtmlTag'), array('tag' => 'td', 'class' => 'element')),
        array('Label', array('placement' => 'PREPEND')),
        array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class'=>'select')),
    );
    
    public function __construct($options = array())
    {
        $this->settings = (object) (!empty($options['settings']) ? $options['settings'] : array());
        parent::__construct($options);
    }

    public function init()
    {
        parent::init();
        //if (!empty($_GET['small_category_list'])) {
        //    $cat = Model_Category::one(array('_id' => new MongoId($_GET['small_category_list'])));
            //$cat = Model_Category::one(array('_id' => new MongoId($cat->path[0])));
            //if ($cat->id == 'mc52') {
            //    $business_directory = true;
            //}
            //else {
                //$business_directory = false;
            //}
        //}
        //else {
            $business_directory = false;
        //}
        // Form for regular Search
        
                $element = new Zend_Form_Element('keyword');
                $element->addFilter('StringTrim');
                $element->setLabel('Keywords');
                $element->setValue((!empty($_GET['keyword']))?$_GET['keyword']:'');
                $element->setDecorators(array(
                    'ViewHelper',
                    'Errors',
                    array('Label', array('placement' => 'PREPEND')),
                    array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class'=>'text')),
               	 	)
                );
                $this->addElement($element);
           
		   	$element = new Zend_Form_Element_Hidden('small_category_list');
	        //$element->setValue((empty($_GET['small_category_list']) ? (!empty($_GET['hidden_small_cat'])?$_GET['hidden_small_cat']:'') : $_GET['small_category_list']));
	        //$element->setValue(empty($_GET['small_category_list']) ? (!empty($_GET['hidden_small_cat'])?$_GET['hidden_small_cat']:'') : $_GET['small_category_list']);
  //          var_dump(Zend_Registry::get('main_cat'));
            if (Zend_Registry::isRegistered('current_category')) {
                $element->setValue(Zend_Registry::get('current_category'));
            }
	        $element->setDecorators(array(
	                'ViewHelper'
	            )
	        );
	        $this->addElement($element);

            /* $element = new Zend_Form_Element_Hidden('small_category_list');
            if (Zend_Registry::isRegistered('category_list_selected')) {
                $selected = Zend_Registry::get('category_list_selected');
                $element->setValue($selected);
            } elseif (!empty($_GET['small_category_list'])) {
                $selected = $_GET['small_category_list'];
                if (isset($values['key_search_tools']['small_category_list']))
                	$selected = $values['key_search_tools']['small_category_list'];
                $element->setValue($selected);
            }
            
            $element->setDecorators(array(
                    'ViewHelper'
                )
            );
            $this->addElement($element);*/

            $form1     = $this->getNewSubForm();           
            
            //Keywords
            /*$form1->addElement('text', 'keywords', array(
                'filters'    => array('StringTrim'),
                'validators' => array(
                    //'EmailAddress',
                ),
                'decorators'  => array(
                    'ViewHelper',
                    'Errors',
                    array('Label', array('placement' => 'PREPEND')),
                    array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class'=>'text')),
                ),
                'required'   => false,
                'label'      => 'Keywords',
                'value'      => (!empty($_GET['keyword']))?$_GET['keyword']:'',
            ));*/
            
            if(strpos($_SERVER["REQUEST_URI"], '/c/')===false){
	            //Category
	            $cats = Model_Category::getLevel1();
	            $result = array('Please Select');
		        foreach ($cats as $cat) {
		        	if($cat->name=="Business Directory"){continue;}
		        	//echo "<pre>";print_r($cat);exit();
		            $result[(string)$cat->_id]=$cat->name;
		        }
	            //echo "<pre>";print_r($cats);exit();
	            
	            $form1->addElement('select', 'small_category_list', array(
	                'filters'    => array('StringTrim'),
	                'Label' => 'Category',
	                'multiOptions'  => $result,
	                'disableLoadDefaultDecorators' => true,
	                'decorators' => $this->selectElementDecorators,
	                'required'   => false,
	                'value'        => $this->getSetting('small_category_list')
	            ));
            }
            
            $locations = array();
            $locs      = Model_Location::all();

            foreach($locs as $k => $loc) {
                if (count($loc['path']) == 1) {
                    $locations[(string) $k] = array('name' => $loc);
                } else {
                    $parent = $loc['path'][0];
                    $tmp    = !empty($locations[(string) $parent]) ? $locations[(string) $parent] : array();

                    $tmp['children'][$k]         = $loc;
                    $locations[(string) $parent] = $tmp;
                }
            }

            //Area
            $area = Model_Location::getAreaSearch();
            $selected_area = $this->getSetting('area');
            if (empty($selected_area)) {
                reset($area);
                $selected_area = key($area);
            }
            /*
            $form1->addElement('select', 'area', array(
                'filters'    => array('StringTrim'),
                'validators' => array(
                    'Alnum',
                    array('StringLength', false, 1),
                ),
                'multiOptions' => $area,
                'Label' => 'Area',
                'disableLoadDefaultDecorators' => true,
                'decorators' => $this->selectElementDecorators,
                'required'   => false,
                'value'        => $this->getSetting('area'),
            ));

             *
             */
            $locations = array('Please Select');
            $locs = Model_Location::all()->sort(array('path' => 1));
            $parent = '';
            foreach($locs as $k => $loc) {

                if (count($loc->path) == 1) {
                    $parent = $loc->name;
                    $locations[$loc->name] = array();
                } else {

                    //$parent = (string) $loc->path[0];
                    $tmp    = !empty($locations[(string) $parent]) ? $locations[(string) $parent] : array();

                    $tmp[$k]         = (string) $loc->name;
                    //echo '<pre>';
                    //print_r($tmp);
                    $locations[(string) $parent] = $tmp;
                }
            }

            //District
            $form1->addElement('select', 'district', array(
                'filters'    => array('StringTrim'),
                'validators' => array(
                    'Alnum',
                    array('StringLength', false, 24),
                ),
                'Label' => 'District',
                'multiOptions'  => $locations,
                'disableLoadDefaultDecorators' => true,
                'decorators' => $this->selectElementDecorators,
                'required'   => false,
                'value'        => $this->getSetting('district')
            ));

            /*
            $form1->addElement('jqslider', 'price', array(
                        'jQueryParams' => array(
                            'min'      => $this->getSetting('price_min') !== null ? $this->getSetting('price_min') : 0,
                            'max'      => $this->getSetting('price_max') !== null ? $this->getSetting('price_max') : 20000000,
                            'values'   => $this->getSetting('price_start') !== null ? $this->getSetting('price_start') : array('0', '20000000'),
                            'currency' => '$HKD',
                            'range'    => true,
                            'step'     => 1000,
                            ),
                        'label'       => 'Price (HKD$)',
                        'decorators'  => array(
                                'Errors',
                                'UiWidgetElement',
                                array('Label', array('escape' => false)),
                                array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'slide')),
                        )
                    )
            );
            */
            if ($business_directory == false) {
                $form1->addElement('textRange', 'price', array(
                            'label'       => 'Price',
                            'value'       => $this->getSetting('price_start') !== null ? $this->getSetting('price_start') : array(),
                            'class'       => array('class' => 'text-range'),
                            'decorators'  => array(
                                    'Errors',
                                    'ViewHelper',
                                    array('Label', array('escape' => false)),
                                    array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'price text pricerange')),
                            )
                        )
                );
                
                $form1->addDisplayGroup(array('price', ), 'key_search_tool',
                    array(
                        'decorators' => $this->displayGroupDecorators
                    )
                );
            }


            /* Has Image 
            $form1->addElement('checkbox', 'has_image', array(
                'filters'    => array('StringTrim'),
                'validators' => array(
                    //'EmailAddress',
                ),
                'decorators' => $this->elementCheckBoxDecorators,
                'attribs'    => array('class' =>'inputCheckBox'),
                'required'   => false,
                'label'      => 'Has an image',
                'value'      => $this->settings->has_image,
            ));

            $deco   = $this->displayGroupDecorators;
            $deco[] = array('Description', array('escape' => false, 'placement' => 'PREPEND', 'tag' => 'span'));
            $deco[] = array(array('innerHTmlTag' => 'HtmlTag'), array('tag' => 'p', 'class' => 'checkbox'));

            $form1->addDisplayGroup(array('has_image'), 'sell_by',
                array(
                    'decorators'  => $deco
                )
            );*/

            //$form1->setLegend('Narrow Your Search');
           // $form1->addDecorator('fieldset', array('class'=> 'key_search'));
           
           	

            $this->addSubForm($form1, 'key_search_tools');

            $form2 = $this->getNewSubForm();
            $form2->setDecorators(
                    array('FormElements')
            );
            // Submit Button
            $form2->addElement('button', 'v', array(
                'required'   => false,
                'ignore'     => true,
                'type'       => 'submit',
                'label'      => 'Go!',
                'decorators'  => array(
                        'Errors',
                        'ViewHelper',
                        array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'button em')),
                )
            ));

            $this->addSubForm($form2, 'key_search_tools2');

    }

    function populate(array $values)
    {
    	
        //Price
        if (isset($values['key_search_tools-price']) && isset($values['key_search_tools-price-1'])) {
            $this->settings->price_start = array($values['key_search_tools-price'], $values['key_search_tools-price-1']);
        }
        if (isset($values['price']) && isset($values['price-1'])) {
            $this->settings->price_start = array($values['price'], $values['price-1']);
        }
        //Area
        if (isset($values['key_search_tools']['area'])) {
            $this->settings->area = $values['key_search_tools']['area'];
        }
        if (isset($values['area'])) {
            $this->settings->area = $_GET['area'];
        }
		 //Category
        if (isset($values['key_search_tools']['small_category_list'])) {
            $this->settings->district = $values['key_search_tools']['small_category_list'];
        }
        if (isset($values['small_category_list'])) {
            $this->settings->district = $_GET['small_category_list'];
        }
        
        //District
        if (isset($values['key_search_tools']['district'])) {
            $this->settings->district = $values['key_search_tools']['district'];
        }
        if (isset($values['district'])) {
            $this->settings->district = $_GET['district'];
        }

        //Has Image
        $this->settings->has_image = !empty($values['has_image']);

        //Keywords
        if (isset($values['key_search_tools']['keyword'])) {
            $this->settings->keyword = $values['key_search_tools']['keyword'];
        }
    }

    private function getNewSubForm()
    {
        $form = new Ac_SubForm();
        $form->setDecorators($this->subFormDecorators);
        $form->setDisplayGroupDecorators($this->displayGroupDecorators);
        return $form;
    }

    private function getSetting($name)
    {
        if (!empty($this->settings->$name) && $this->settings->$name != '*') {
            return $this->settings->$name;
        }
        return null;
    }

    public function __toString()
    {
        $str = '
            $j("#key_search_tools-area").change(function (event) {
                event.stopImmediatePropagation();
                $j.get("/search/get-attribute", { c:"area", f:"district_bis", id: $j("#key_search_tools-area").val() },
                    function(data) {
                        $j("#key_search_tools-district").empty();
                        $j.each(data, function (index, value) {
                            $(document.createElement("option"))
                                .html(value)
                                .attr("value", index)
                                .appendTo($("#key_search_tools-district"));
                        });
                    });
           });
        ';
        $this->view->JQuery()->addJavascript($str);
        return parent::__toString();
    }
}
